package com.lx.dao.imp;

import com.lx.dao.BaseAdminDao;
import com.lx.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * @ClassName: AdminDaoMysql
 * @Description:
 * @Date Created in  2021-07-06 8:58
 * @Modified By:
 * @Author: 零巽
 */
public class AdminDaoMysql implements BaseAdminDao {

    private static final String SQL_UPDATE_LOGIN_TIME = "update Eadmin set loginTime=?,LoginIp=? where userName=?";
    private static final String SQL_LOGIN ="select Id from Eadmin where userName=? and password=?" ;

    /**
     * 根据账号更新登录时间和登录ip的方法
     *
     * @param userName 账号
     * @param date     登录时间
     * @param ip       登录ip
     */
    @Override
    public void UpdateLoginTime(String userName, Date date, String ip) {
        //获得连接
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement = null;
        //预编译sql语句
        try {
            preparedStatement = connection.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            //传入参数
            preparedStatement.setDate(1,new java.sql.Date(date.getTime()));
            preparedStatement.setString(2, ip);
            preparedStatement.setString(3, userName);
            //执行
            preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //关闭资源
            DruidUtil.close(connection,preparedStatement,null);
        }
    }

    /**
     * 根据账号密码登录的方法
     *
     * @param userName 账号
     * @param password 密码
     * @return 返回是否登录成功
     */
    @Override
    public boolean Login(String userName, String password) {
        //获得连接
        Connection connection = DruidUtil.getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet =null;
        //预编译sql语句
        try {
            preparedStatement = connection.prepareStatement(SQL_LOGIN);
            //传入参数
            preparedStatement.setString(1, userName);
            preparedStatement.setString(2,password);
            //执行
            resultSet = preparedStatement.executeQuery();
            //根据查询结果return
            return resultSet.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //关闭资源
            DruidUtil.close(connection,preparedStatement,null);
        }
        return false;
    }
}
